package com.xuecheng.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:王亚栋
 * @Date: 2023/7/9 下午12:41
 * @Version:1.0
 * 全局异常处理器
 */
@ControllerAdvice
@Slf4j(topic = "GlobalExceptionHandler")
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(XCPlusException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse customException(XCPlusException e){


        //记录异常
        log.error("系统异常{}",e.getMessage(),e);

        //解析异常信息
        String errMessage = e.getMessage();

        RestErrorResponse restErrorResponse = new RestErrorResponse(errMessage);

        return restErrorResponse;
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse exception(Exception e){

        //记录异常
        log.error("系统异常{}",e.getMessage(),e);

        if (e.getMessage().equals("不允许访问")){

            return new RestErrorResponse("您没有权限操作此方法！");
        }

        RestErrorResponse restErrorResponse = new RestErrorResponse(CommonError.UN_KNOW_ERROR.getErrMessage());

        return restErrorResponse;
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse MethodArgumentNotValidException(MethodArgumentNotValidException e){

        BindingResult bindingResult = e.getBindingResult();

        //存放错误信息
        List<String> errors = new ArrayList<>();

        bindingResult.getFieldErrors().stream().forEach(item -> {

            errors.add(item.getDefaultMessage());
        });

        //将list中的错误信息拼接起来
        String errMsg = StringUtils.join(errors, ",");
        //记录异常
        log.error("系统异常{}",e.getMessage(),errMsg);

        RestErrorResponse restErrorResponse = new RestErrorResponse(errMsg);

        return restErrorResponse;

    }


}
